package com.jinlejia.erp.ui.house.prospect;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.prospect.UploadHouseTypeImageAdapter;
import com.jinlejia.erp.adapter.prospect.UploadImageGridViewAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.databinding.ActivityProspectViewPictureBinding;
import com.weight.CustomToast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Locale;

import uk.co.senab.photoview.PhotoView;

/**
 * 预览户型图
 */
public class ProspectViewPictureActivity extends AppCompatActivity {

    public static final String PARAM_URLS = "PARAM_URLS";

    public static final String PARAM_POSITION = "PARAM_POSITION";

    public static final String PARAM_SOURCES = "PARAM_SOURCES";

    public static final String PARAM_SELECT_POSITION = "PARAM_SELECT_POSITION";

    private ArrayList<UploadHouseTypeImageAdapter.HouseTypeSource> urls;
    private ArrayList<UploadImageGridViewAdapter.Source> sources;
    private int mPosition;
    private int mSelectedPosition =-1;
    private ActivityProspectViewPictureBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_prospect_view_picture);
        binding.saveButton.setOnClickListener(v->save());
        binding.chooseImage.setOnClickListener(v->choose());
        binding.backImageView.setOnClickListener(v->backView());
        Intent intent = getIntent();
        urls = intent.getParcelableArrayListExtra(PARAM_URLS);
        sources = intent.getParcelableArrayListExtra(PARAM_SOURCES);
        if (sources!=null){
            for (UploadImageGridViewAdapter.Source s:sources) {
                if (TextUtils.isEmpty(s.getServerUrl())){
                    sources.remove(s);
                }
            }
        }
        mPosition = intent.getIntExtra(PARAM_POSITION,0);
        mSelectedPosition = intent.getIntExtra(PARAM_SELECT_POSITION,-1);
        binding.save.setOnClickListener(v -> new getImageCacheAsyncTask(ProspectViewPictureActivity.this)
                .execute(ApiConfig.MAGEHEADER_URL()+sources.get(mPosition).getPictureUrl()));
        //region init
        if (urls!=null){
            String title = "预览 %s/%s";
            binding.save.setVisibility(View.GONE);
            binding.viewLabelTextView.setVisibility(View.GONE);
            binding.saveButton.setVisibility(View.VISIBLE);
            title = String.format(Locale.CHINESE,title,String.valueOf(mPosition+1),urls.size());
            binding.titleTextView.setText(title);
            if (mSelectedPosition == mPosition){
                binding.chooseImage.setImageResource(R.mipmap.circle_selected);
            }else {
                binding.chooseImage.setImageResource(R.mipmap.circle_normal);
            }
            updateButton();
        }else if (sources!=null){
            String title = "预览 %s/%s";
            title = String.format(Locale.CHINESE,title,String.valueOf(mPosition+1),sources.size());
            binding.titleTextView.setText(title);
            binding.save.setVisibility(View.VISIBLE);
            binding.viewLabelTextView.setVisibility(View.GONE); //取消分间信息的提示
            UploadImageGridViewAdapter.Source source = sources.get(mPosition);
            binding.viewLabelTextView.setText(source.getHouseInfo());
            binding.saveButton.setVisibility(View.GONE);
            binding.chooseImage.setVisibility(View.GONE);
        }

        //endregion

        SamplePagerAdapter mAdapter = new SamplePagerAdapter();
        binding.viewPager.setAdapter(mAdapter);
        binding.viewPager.setCurrentItem(mPosition);
        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mPosition = position;
                String title = "预览 %s/%s";

                if (urls != null){
                    UploadHouseTypeImageAdapter.HouseTypeSource source = urls.get(position);
                    if (mSelectedPosition ==position){
                        source.setChecked(true);
                        binding.chooseImage.setImageResource(R.mipmap.circle_selected);
                    }else {
                        source.setChecked(false);
                        binding.chooseImage.setImageResource(R.mipmap.circle_normal);
                    }
                    title = String.format(Locale.CHINESE,title,String.valueOf(position+1),urls.size());
                }else if (sources != null){
                    UploadImageGridViewAdapter.Source source = sources.get(position);
                    binding.viewLabelTextView.setText(source.getHouseInfo());
                    title = String.format(Locale.CHINESE,title,String.valueOf(position+1),sources.size());
                }
                binding.titleTextView.setText(title);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void switchCheck(int position){
        UploadHouseTypeImageAdapter.HouseTypeSource source = urls.get(position);
        if (!source.isChecked()){
            this.mSelectedPosition = position;
            binding.chooseImage.setImageResource(R.mipmap.circle_selected);
        }else {
            this.mSelectedPosition = -1;
            binding.chooseImage.setImageResource(R.mipmap.circle_normal);
        }
        source.setChecked(!source.isChecked());
        updateButton();
    }

    private void updateButton(){
        if (mSelectedPosition != -1){
            binding.saveButton.setEnabled(true);
        }else {
            binding.saveButton.setEnabled(false);
        }
    }

    public void save(){
        Intent intent = new Intent();
        intent.putExtra("selectPosition",this.mSelectedPosition);
        intent.putExtra("save",true);
        setResult(Activity.RESULT_OK,intent);
        super.finish();
    }

    public void choose(){
        switchCheck(binding.viewPager.getCurrentItem());
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        intent.putExtra("selectPosition",this.mSelectedPosition);
        setResult(Activity.RESULT_OK,intent);
        super.finish();
    }

    public void backView(){

        finish();
    }


    private class SamplePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (urls!=null){
                return urls.size();
            }else if (sources!=null){
                return sources.size();
            } else{
                return 1;
            }
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            String url;
            if (urls!=null){
                UploadHouseTypeImageAdapter.HouseTypeSource source = urls.get(position);
                url = source.getImageUrl();
            }else /*if (sources!=null)*/{
                UploadImageGridViewAdapter.Source source = sources.get(position);
                url = source.getPictureUrl();
            }
            int indexOf = url.indexOf(File.separator);
            if (indexOf==-1){
                url = ApiConfig.MAGEHEADER_URL() + url;
            }
            Glide.with(ProspectViewPictureActivity.this).load(url).placeholder(R.mipmap.ic_no_img).into(photoView);
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final Context context;

        public getImageCacheAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl =  params[0];
            try {
                return Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            //此path就是对应文件的缓存路径
            String path = result.getPath();
            Bitmap bmp = BitmapFactory.decodeFile(path);
            if (bmp != null ){
                SavePicture(bmp);
                CustomToast.showToast(ProspectViewPictureActivity.this,"保存成功",2000);
            }else {
                CustomToast.showToast(ProspectViewPictureActivity.this,"保存失败",2000);
            }

        }

        private void SavePicture(Bitmap bitmap) {
            File appDir = new File(Environment.getExternalStorageDirectory(), "HouseTypePicture");//在SD卡中创建一个文件夹
            if (!appDir.exists()) {//如果该文件夹不存在，则创建一个文件夹
                appDir.mkdir();
            }
            try {
                String fileName = System.currentTimeMillis() + ".jpg";
                File file = new File(appDir, fileName);
                FileOutputStream out;
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG,100, out);
                out.flush();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                ProspectViewPictureActivity.this.sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
